<?php
/**
* 将字符串转换为数组
*
* @param	string	$data	字符串
* @return	array	返回数组格式，如果，data为空，则返回空数组
*/
function string2array($data) {
	if($data == '') return array();
	@eval("\$array = $data;");
	return $array;
}
/**
* 将数组转换为字符串
*
* @param	array	$data		数组
* @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
* @return	string	返回字符串，如果，data为空，则返回空
*/
function array2string($data, $isformdata = 1) {
	if($data == '') return '';
	if($isformdata) $data = new_stripslashes($data);
	return addslashes(var_export($data, TRUE));
}

/**
  * 返回经stripslashes处理过的字符串或数组
  * @param $string 需要处理的字符串或数组
  * @return mixed
  */
 function new_stripslashes($string) {
     if(!is_array($string)) return stripslashes($string);
     foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
     return $string;
 }

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	return $string;
}
/**
 * 转义 javascript 代码标记
 *
 * @param $str
 * @return mixed
 */
 function trim_script($str) {
	if(is_array($str)){
		foreach ($str as $key => $val){
			$str[$key] = trim_script($val);
		}
 	}else{
 		$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
		$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
		$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
		$str = preg_replace ( '/]]\>/si', ']] >', $str );
 	}
	return $str;
}
/**
 * 获取当前页面完整URL地址
 */
function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}
/**
 * @brief 获取网站根路径
 * @param  string $protocol 协议  默认为http协议，不需要带'://'
 * @return String $baseUrl  网站根路径
 *
 */
function getHost($protocol='http')
{
	$port    = $_SERVER['SERVER_PORT'] == 80 ? '' : ':'.$_SERVER['SERVER_PORT'];
	$host	 = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
	$baseUrl = $protocol.'://'.$host.$port;
	return $baseUrl;
}
/**
 * 数组保存到文件
 * @param string $filename 文件地址
 * @param array	 $arr 保存的数组
 */ 
function array2file($filename, $arr='array()'){
	if(is_array($arr)){
		$con = var_export($arr,true);
	} else{
		$con = $arr;
	}
	$con = "<?php\nreturn $con;\n?>";//\n!defined('IN_MP') && die();\nreturn $con;\n
	write_file($filename, $con);
}

/**
 * 创建多级目录
 * @param string $dirs	多级目录
 * @param int $mode	权限
 */
function mkdirs($dirs, $mode=0775) {
	if(!is_dir($dirs)){
		mkdirs(dirname($dirs), $mode);
		return @mkdir($dirs, $mode);
	}
	return true;
}

function write_file($l1, $l2=''){
	$dir = dirname($l1);
	if(!is_dir($dir)){
		mkdirs($dir);
	}
	return @file_put_contents($l1, $l2);
}

function read_file($l1){
	return @file_get_contents($l1);
}


//获得某天前的最后一秒时间戳
function xtime( $day ){
	$day = intval($day);
	return mktime(23,59,59,date("m"),date("d")-$day,date("y"));
}

// 获取相对目录
function get_base_path( $filename ){
    $base_path = $_SERVER['PHP_SELF'];
    $base_path = substr($base_path,0,strpos($base_path,$filename));
	return $base_path;
}

// 获取相对路径
function get_base_url($baseurl, $url){
	if("#" == $url){
		return "";
	}elseif(FALSE !== stristr($url,"http://")){
		return $url;
	}elseif( "/" == substr($url,0,1) ){
		$tmp = parse_url($baseurl);
		return $tmp["scheme"]."://".$tmp["host"].$url;
	}else{
		$tmp = pathinfo($baseurl);
		return $tmp["dirname"]."/".$url;
	}
}

//输入过滤 同时去除连续空白字符可参考扩展库的remove_xss
function get_replace_input( $str, $rptype = 0 ){
	$str = stripslashes($str);
	$str = htmlspecialchars($str);
	$str = get_replace_nb($str);
	return addslashes($str);
}

//去除换行
function get_replace_nr( $str ){
	$str = str_replace(array("<nr/>","<rr/>"),array("\n","\r"),$str);
	return trim($str);
}

//去除连续空格
function get_replace_nb( $str ){
	$str = str_replace("&nbsp;",' ',$str);
	$str = str_replace("　",' ',$str);
	$str = ereg_replace("[\r\n\t ]{1,}",' ',$str);
	return trim($str);
}

//去除所有标准的HTML代码
function get_replace_html($str, $start=0, $length, $charset="utf-8", $suffix=false){
	return msubstr(eregi_replace('<[^>]+>','',ereg_replace("[\r\n\t ]{1,}",' ',get_replace_nb($str))),$start,$length,$charset,$suffix);
}

//正则提取正文里指定的第几张图片地址
function get_image_in_content($content, $number = 1){
	preg_match_all('/<img(.*?)src="(.*?)(?=")/si',$content,$imgarr);
	preg_match_all('/(?<=src=").*?(?=")/si',implode('" ',$imgarr[0]).'" ',$imgarr);
	$countimg = count($imgarr);
	if($number > $countimg){
		$number = $countimg;
	}
	return $imgarr[0][($number-1)];
}

/**
 * 货币显示
 * @param float $value	价格
 * @param string $type	货币符号
 * @param bool $showSymbol	是否显示货币符号
 * @param string $currency	货币代码
 */
function currency($value, $type = "CNY", $showSymbol = true, $currency = null)
{
  static $n = null, $symbol = '', $isleft = 1;
  if(!$currency) $currency = $_SESSION['currency'];

  if (!isset($n)) {
    if (!isset($currencies)) {
      $currencies = SiteModel::currency_list();
    }
    if (!isset($default)) {
      $default = C('currency');
    }
    $n = 1;
    if ($default && isset($currencies[$default])) {
      $symbol = $currencies[$default]['symbol'];
      $isleft = $currencies[$default]['isleft'];
      if (isset($type) && isset($currencies[$type])) {
      } else if (isset($currency) && isset($currencies[$currency])) {
        $type = $currency;
      } else {
        $type = false;
      }
      if ($type && $type != $default) {
        $symbol = $currencies[$type]['symbol'];
        $isleft = $currencies[$type]['isleft'];
        $n = $currencies[$default]['exchange'] / $currencies[$type]['exchange'];
      }
    }
  }
  $value /= $n;
  $result = ($currency == 'JPY') ? number_format($value, 0, '.', '') : number_format($value, 2, '.', '');
  if($showSymbol){
  	if($isleft){
  		 $result = $symbol . $result;
  	}else{
  		$result = $result.' '.$symbol;
  	}
  }
  return $result;
}

//截取字符串
function strwidth($str, $width, $marker = '...')
{
  return mb_strimwidth($str, 0, $width, $marker, 'UTF8');
}

/**
 * 获取URL链接
 * @param String $type 类型
 * @param Array $vars 链接参数(字符串或者数组)
 * @return String 返回URL
 */
function url($type='', $vars='', $suffix=true){
	if(empty($type)){
		return (is_ssl()?'https://':'http://').strtolower($_SERVER['HTTP_HOST']) . '/';
	}
	switch ($type){
		case 'category':
			$url ='/category';
			break;
		case 'product_info':
			$url = '/product';
			break;
		case 'article_help':
			$url = '/help';
			break;
		case 'article_type':
			$url = '/article/list';
			break;
		case 'article_info':
			$url = '/article';
			break;
		default: $url = $type;
	}
	return U($url, $vars, $suffix, false, true);
}

/**
 * 对数组反转义
 * @param array $array
 */
if(!function_exists('stripslashes_deep')){
	function stripslashes_deep($value)
	{
	    $value = is_array($value) ?
	                array_map('stripslashes_deep', $value) :
	                stripslashes($value);
	    return $value;
	}
}
//url特殊符号处理
	function generateUrl_un($str) {
		$url = urlencode(preg_replace('/[\.|\/|\?|&|\+|\\\|\'|"|,]+/','-', strtolower(trim($str))));
		$url = str_replace('+', '-', $url);
		$url = str_replace('%', '-', $url);
		$url = str_replace('__', '-', $url);
		$url = str_replace('-.', '-', $url);
		$url = str_replace(' ', '-', $url);
		return $url;
		}

/**
 * 获取IP地址 
 * 从ownonlygateway.php移出来的
 * @return String 返回ip地址
 */		
function real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}
    //判断是否是移动设备
    function check_wap(){
        // 先检查是否为wap代理，准确度高
        if(stristr($_SERVER['HTTP_VIA'],"wap")){
            return true;
        }
        // 检查浏览器是否接受 WML.
        elseif(strpos(strtoupper($_SERVER['HTTP_ACCEPT']),"VND.WAP.WML") > 0){
            return true;
       }
       //检查USER_AGENT
       elseif(preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])){
            return true;            
        }
        else{
            return false;   
       }
    }
    //ipad  手机端  pc端
    function  check_wap2(){
        $agent= $_SERVER['HTTP_USER_AGENT'];
        if(strpos($agent,"iPad")){
            return 1;//ipad
        }else if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){
            return 2;//手机
        }else{
            return 0;//pc端
        }
    }
//生成一个随机优惠码
function get_str_coupon($num){
    $str="1234567890abcdefghijklmnopqretuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $str=substr(str_shuffle($str),0,$num);
    return $str;
}
?>